<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
class Coupondetail_model extends CI_Model {
	public function __construct() {
		parent::__construct ();
	}
	/*
	 * 返回所有优惠券的数量
	 */
	public function count_coupondetails(){
		$query = $this->db->get('t_coupondetail');
		return $query->num_rows();
	}
	/*
	 * 根据分页信息得到优惠券
	 */
	public function find_all_coupondetails($per_page,$offset){
		$this->db->select('t_coupondetail.id,t_coupondetail.couponno,t_coupondetail.userid,t_coupondetail.state,,t_coupon.more,t_coupon.off');
		$this->db->from('t_coupondetail');
		$this->db->join('t_coupon', 't_coupondetail.couponid = t_coupon.id','left');
		$this->db->limit($per_page, $offset);
		$this->db->order_by("id", "desc");
		$query = $this->db->get();
		return $query->result_array();
	}
	/*
	 * 根据优惠券ID得到优惠券信息
	 */
	public function load($id){
		$this->db->select('t_coupondetail.id,t_coupondetail.couponno,t_coupondetail.userid,t_coupon.more,t_coupon.off');
		$this->db->from('t_coupondetail');
		$this->db->where('t_coupondetail.id', $id);
		$this->db->join('t_coupon', 't_coupondetail.couponid = t_coupon.id','left');
		$query = $this->db->get();
		return $query->row_array();
	}
   /*
	 * 添加优惠券信息
	 */
	public function create($coupon){
		$this->db->insert('t_coupondetail', $coupon);
		return $this->db->insert_id();
	}
	 /*
	 * 更新优惠券信息
	 */
	public function update($id,$coupon){
		$this->db->where('id', $id);
		$this->db->update('t_coupondetail', $coupon);
		return $this->db->affected_rows()>0;
	}
	 /*
	 * 删除优惠券信息
	 */
	public function delete($id){
		$this->db->where('id', $id);
		$this->db->delete('t_coupondetail');
		return $this->db->affected_rows()>0;
	}
	/*
	 * 检查优惠券号码是否存在
	 */
	public function check_couponno($couponno){
		//$this->db->select('id');
		$query = $this->db->get_where('t_coupondetail',array('couponno' => $couponno));
		if ($query->row_array()){
			return true;
		}
		return false;
	}
	/*
	 * 根据用户ID和优惠券类型ID得到优惠券(用于首单赠送优惠券)
	 */
	public function find_by_useridandcouponid($userid,$couponid){
		$this->db->where('userid', $userid);
		$this->db->where('couponid', $couponid);
		$query = $this->db->get('t_coupondetail');
		return $query->row_array();
	}
	/*
	 * 根据用户ID得到优惠券信息
	 */
	public function get_coupondetailsbyuser($userid){
		$this->db->select('t_coupondetail.id,t_coupondetail.couponno,t_coupondetail.state,t_coupon.more,t_coupon.off,t_coupon.starttime,t_coupon.endtime,t_user.shopname');
		$this->db->from('t_coupondetail');
		$this->db->where('t_coupondetail.userid',$userid);
		$this->db->join('t_coupon', 't_coupondetail.couponid = t_coupon.id','left');
		$this->db->join('t_user', 't_coupondetail.userid = t_user.id','left');
		$this->db->order_by("id", "desc");
		$query = $this->db->get();
		return $query->result_array();
	}
}